﻿using Auth0;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WorkBasket.Data.Entities;
using WorkBasket.Data.Repository;
using WorkBasket.Infrastructure;
using WorkBasket.Models;

namespace WorkBasket.Controllers.Api
{
    public class InviteController : ApiController
    {

        private SOC soc = new SOC(new MyContext());

           [Route("api/Invite/GetReceivedInvitesByCurrentUserID")]
        public IHttpActionResult GetReceivedInvitesByCurrentUserID()
        {
            DashModel dm = new DashModel();


            return Json(dm.NewInvitations);
        }
 
        [Route("api/Invite/save")]
        public IHttpActionResult Post([FromBody]  Invite value)
        {

            
            try
            {
                string message = string.Empty   ;


      
                
                bool IsNew = false;
                if (value.InviteID == 0)
                {
                    
                    value.DateSent = DateTime.Now;
                    value.UniqueID = Guid.NewGuid();
                    value.SentBy = User.Identity.Name;
                    value.SentUserID = AuthFunctions.CurrentUserID();
                    soc.Invites.Add(value);
                    IsNew = true;
                    message = "Invitation sent";
                }
                else
                {
                    message = "Invite updated";
                    soc.Invites.Update(value);
                }
                soc.CommitChanges();
                if(IsNew) //down here to ensure invite saves
                {
                    int EmailID = Convert.ToInt32(soc.Settings.Where(c => c.SettingName == "InviteEmailID").First<Setting>().SettingValue);
                    Email email = soc.Emails.GetByID(EmailID);
                    email.To = value.EMail;
                    var request = HttpContext.Current.Request;
                    email.Body = email.Body.Replace("~URL", request.Url.Authority);
                    email.Body = email.Body.Replace("~UniqueID", value.UniqueID.ToString());



                    Emailer emailer = new Emailer();
                    emailer.SendMail(email);

                }


                return Json(new DataReturn(message, value));
            }
            catch (Exception e)
            {
                return Json(new DataReturn(e.Message, value));
            }
        }

    }
}
